﻿using AuthTemplate.DTO.User;
using AuthTemplate.Infrastructure;
using AuthTemplate.Infrastructure.Token;
using AuthTemplate.ViewModel;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace AuthTemplate.MVC.Filter
{
    public class LoginFilter : AuthorizeAttribute
    {
        private static string _indexHtmlUrl = ConfigurationManager.AppSettings["IndexHtmlUrl"];

        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            #region 判断是否存在token

            string token = filterContext.HttpContext.Request.Headers["Authorization"];
            if (!string.IsNullOrEmpty(token) && token.Length > 7 && token.StartsWith("Bearer "))
            {
                token = token.Substring(7).Trim();
            }
            else
            {
                filterContext.Result = GetRedirectDto("请重新登录再操作!", _indexHtmlUrl);
                return;
            }//token异常重定向到login页面

            #endregion

            #region 判断token是否过期或者篡改

            try
            {
                TokenInfo tokenInfo = CommonToken.DecodeToken(token, true);
            }
            catch (Exception ex)
            {
                filterContext.Result = GetRedirectDto("不好意思,登录超时,请重新登录再操作!" , _indexHtmlUrl);
                return;
            }//token异常重定向到login页面

            #endregion

            #region 对action的权限控制



            #endregion

        }

        /// <summary>
        /// 获取跳转到login的dto
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        private ContentResult GetRedirectDto(string message,string htmlUrl)
        {
            MyResponse<RedirectDto> output = new MyResponse<RedirectDto>()
            {
                Code = 302,
                Message = message,
                data = new RedirectDto()
                {
                    Url = htmlUrl
                }
            };
            ContentResult Result = new ContentResult()
            {
                Content = JsonHelper.Serialize(output),
                ContentEncoding = Encoding.GetEncoding("UTF-8"),
                ContentType = "application/json"
            };
            return Result;
        }
    }
}